package com.example.demo.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * 中文拼音工具类.
 *
 * @author Li Zhiyuan
 * @since 2020/9/7
 */
public class ChinesePinYinUtil {
    /**
     * 得到 汉字的全拼
     */
    public static String getPingYin(String src){
        HanyuPinyinOutputFormat format=new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder sb=new StringBuilder();
        char[] srcArray=src.toCharArray();
        try {
            for (int i=0;i<srcArray.length;i++){
                //判断是否为汉字字符
                if(java.lang.Character.toString(srcArray[i]).matches("[\\u4E00-\\u9FA5]+")){
                    String[] targaetArray= PinyinHelper.toHanyuPinyinStringArray(srcArray[i],format);
                    sb.append(targaetArray[0]);
                }else {
                    sb.append(java.lang.Character.toString(srcArray[i]));
                }
            }
            return sb.toString();
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 得到中文首字母
     */
    public static String getPinYinHeadChar(String str){
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<str.length();i++){
            char word=str.charAt(i);
            String[] pinyinArray=PinyinHelper.toHanyuPinyinStringArray(word);
            if(pinyinArray!=null){
                sb.append(pinyinArray[0].charAt(0));
            }else {
                sb.append(word);
            }
        }
        return sb.toString();
    }

    @Test
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String str=sc.next();
        System.out.println(getPingYin(str));
        System.out.println(getPinYinHeadChar(str));
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println(format.format(new Date()));
    }
}

















